using Glpt.Common;
using Glpt.Data;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Runtime.InteropServices;

namespace Glpt.Task
{
    /// <summary>
    /// 文件路径信息
    /// </summary>
    public class FilePath
    {
        [DllImport("kernel32.dll")]
        public static extern IntPtr _lopen(string lpPathName, int iReadWrite);
        [DllImport("kernel32.dll")]
        public static extern bool CloseHandle(IntPtr hObject);
        public const int OF_READWRITE = 2;
        public const int OF_SHARE_DENY_NONE = 0x40;
        public static readonly IntPtr HFILE_ERROR = new IntPtr(-1);

        /// <summary>
        /// 检测文件是否存在
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <param name="tradedate">日期</param>
        /// <param name="check_use">是否检测使用</param>
        public static int CheckFile(string sql, string tradedate, bool check_use)
        {
            int isover = 1;
            try
            {
                BaseInterFace bif = new BaseInterFace();
                DataTable dt = bif.ExecSelect(sql);
                if (dt.Rows.Count == 0)
                    return 0;
                if (!dt.Columns.Contains("PATH_NAME"))
                    AddColumns(dt);
                Dictionary<string, string> dateCache = new Dictionary<string, string>();//缓存
                foreach (DataRow dr in dt.Rows)
                {
                    string BUSI_DATE = tradedate;
                    if (dt.Columns.Contains("DATE_EXP"))
                    {
                        BUSI_DATE = CommFuns.GetDateExpResult(bif, dr["DATE_EXP"].ToString().Trim(), tradedate, dateCache);
                    }
                    string PATH_NAME = Funcs.ReplaceWord(dr["PATH_NAME"].ToString(), BUSI_DATE);
                    string[] FLAG_NAME_LIST = Funcs.ReplaceWord(dr["FLAG_NAME"].ToString(), BUSI_DATE).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string FLAG_NAME in FLAG_NAME_LIST)
                    {
                        isover = CheckFileExist(PATH_NAME, FLAG_NAME, check_use);
                        if (isover == 0)
                            break;
                    }
                    if (isover == 0)
                        break;
                }
            }
            catch
            {
                isover = 0;
            }
            return isover;
        }

        /// <summary>
        /// 检测文件是否存在
        /// </summary>
        /// <param name="filename">文件路径</param>
        /// <param name="check_use">是否检测使用</param>
        /// <returns>是否存在</returns>
        public static int CheckFileExist(string filename, bool check_use)
        {
            string PATH_NAME = "";
            string FLAG_NAME = "";
            if (IsFTP(filename))
                PATH_NAME = filename;
            else
            {
                int idx = filename.LastIndexOf(DataFuns.DirSeparator);
                if (idx > 0)
                {
                    PATH_NAME = filename.Substring(0, idx);
                    FLAG_NAME = filename.Substring(idx + 1);
                }
                else
                {
                    FLAG_NAME = filename;
                }
            }
            return CheckFileExist(PATH_NAME, FLAG_NAME, check_use);
        }

        public static bool IsURL(string url)
        {
            return url.ToLower().StartsWith("http://") || url.ToLower().StartsWith("https://");
        }

        public static bool IsFTP(string url)
        {
            return url.ToLower().StartsWith("ftp://") || url.ToLower().StartsWith("sftp://");
        }
        /// <summary>
        /// 检测文件是否存在
        /// </summary>
        /// <param name="PATH_NAME">目录名</param>
        /// <param name="FLAG_NAME">文件名</param>
        /// <param name="check_use">是否检测使用</param>
        /// <returns>是否存在</returns>
        public static int CheckFileExist(string PATH_NAME, string FLAG_NAME, bool check_use)
        {
            int isover = 1;
            if (IsFTP(PATH_NAME))
            {
                FtpServerInfo ser = new FtpServerInfo(PATH_NAME);
                ser.UsePassive = !check_use;
                List<string> lst = ser.GetFileList();
                if (lst.Count == 0) isover = 0;
            }
            else if (PATH_NAME.Length == 2 && PATH_NAME.EndsWith(":"))
            {
                string filename = PATH_NAME + DataFuns.DirSeparator + FLAG_NAME;
                if (!File.Exists(filename))
                {
                    isover = 0;
                }
                else if (check_use)
                {
                    if (CheckUsing(filename))
                    {
                        isover = 0;
                    }
                }
            }
            else
            {
                if (!Directory.Exists(PATH_NAME))
                {
                    isover = 0;
                }
                else
                {
                    string[] files = Directory.GetFiles(PATH_NAME, FLAG_NAME, SearchOption.TopDirectoryOnly);
                    if (files.Length == 0)
                    {
                        isover = 0;
                    }
                    else if (check_use)
                    {
                        foreach (string filename in files)
                        {
                            if (CheckUsing(filename))
                            {
                                isover = 0;
                                break;
                            }
                        }
                    }
                }
            }
            return isover;
        }

        private static void AddColumns(DataTable dt)
        {
            dt.Columns.Add("PATH_NAME");
            dt.Columns.Add("FLAG_NAME");
            foreach (DataRow dr in dt.Rows)
            {
                string PATH1 = "";
                if (dt.Columns.Contains("PATH1")) PATH1 = dr["PATH1"].ToString();
                string PATH2 = "";
                if (dt.Columns.Contains("PATH2")) PATH2 = dr["PATH2"].ToString();
                string column_value = dr[0].ToString();
                column_value = Path.Combine(PATH1, PATH2, column_value);
                int idx = column_value.LastIndexOf(DataFuns.DirSeparator);
                if (idx > 0)
                {
                    dr["PATH_NAME"] = column_value.Substring(0, idx);
                    dr["FLAG_NAME"] = column_value.Substring(idx + 1);
                }
                else
                {
                    dr["PATH_NAME"] = column_value;
                    dr["FLAG_NAME"] = "*.*";
                }
            }
            dt.AcceptChanges();
        }
        /// <summary>
        /// 文件是否正在使用中
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns>是否使用</returns>
        private static bool CheckUsing(string filename)
        {
            bool ret = false;
            if (File.Exists(filename))
            {
                IntPtr vHandle = _lopen(filename, OF_READWRITE | OF_SHARE_DENY_NONE);
                if (vHandle == HFILE_ERROR)
                {
                    ret = true;
                }
                else
                    CloseHandle(vHandle);
            }
            return ret;
        }
    }
}
